package com.credithc.eagleeye.plugins.util;
import com.credithc.eagleeye.agent.bean.EagleEyeAgentConfig;
import com.credithc.eagleeye.agent.factory.EagleEyeAgentFactory;
import com.credithc.eagleeye.agent.util.HostUtil;
import com.credithc.eagleeye.util.FastJsonConvert;
import com.credithc.eagleeye.vo.RpcTraceInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2020年01月03日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Slf4j
public class LogUtil {
    private static String SPLUNK_LOG_FORMAT = "";

    static{
        StringBuilder builder = new StringBuilder();
        builder.append("eagle-eye-log: ");
        builder.append("clientName=%s");//clientName
        builder.append(", platformName=%s");//platformName
        builder.append(", userInfo=%s");//userInfo
        builder.append(", rpcType=%s");//rpcType
        builder.append(", serviceCategory=%s");//serviceCategory
        builder.append(", serviceName=%s");//serviceName
        builder.append(", methodName=%s");//methodName
        builder.append(", clientHost=%s");//clientHost
        builder.append(", serverHost=%s");//serverHost
        builder.append(", result=%s");//result
        builder.append(", requestSize=%s");//requestSize
        builder.append(", responseSize=%s");//responseSize
        builder.append(", runTime=%s");//runTime
        SPLUNK_LOG_FORMAT = builder.toString();
    }

    public static void printSplunkLog(RpcTraceInfoVo rpcTraceInfoVo) {
        EagleEyeAgentConfig eagleEyeAgentConfig = EagleEyeAgentFactory.getInstance().getEagleEyeAgentConfig();
        if (eagleEyeAgentConfig.isEnablePrintLog()) {
            log.info(String.format(SPLUNK_LOG_FORMAT,
                     eagleEyeAgentConfig.getAgentClientName(),
                     eagleEyeAgentConfig.getAgentPlatform(),
                     rpcTraceInfoVo.getUserInfo()==null?"null": FastJsonConvert.convertObjectToJSON(rpcTraceInfoVo.getUserInfo()),
                     rpcTraceInfoVo.getRpcType(),
                     rpcTraceInfoVo.getServiceCategory(),
                     rpcTraceInfoVo.getServiceName(),
                     rpcTraceInfoVo.getMethodName(),
                     StringUtils.isBlank(rpcTraceInfoVo.getClientHost())? HostUtil.getIp() :rpcTraceInfoVo.getClientHost(),
                     rpcTraceInfoVo.getServerHost(),
                     rpcTraceInfoVo.getResult(),
                     rpcTraceInfoVo.getRequestSize(),
                     rpcTraceInfoVo.getResponseSize(),
                     rpcTraceInfoVo.getRunTime()
                    )
            );
        }
    }

}
